package com.smarthealthring.mm.base;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatDelegate;
import android.view.ViewGroup;

import com.baidu.mobstat.StatService;
import com.smarthealthring.mm.App;
import com.smarthealthring.mm.R;
import com.smarthealthring.mm.widgets.LoadingDialog;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by hewei26 on 2017/4/18.
 */

public abstract class BaseActivity<T extends IPresenter> extends RxAppCompatActivity implements IView {
    protected T mPresenter;
    protected Activity mContext;
    private Unbinder mUnBinder;

    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

    public ViewGroup getRootView(Activity context) {
        return (ViewGroup) ((ViewGroup) context.findViewById(android.R.id.content)).getChildAt(0);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayout());
        mUnBinder = ButterKnife.bind(this);
        mContext = this;

        if (mPresenter == null) {
            mPresenter = createPresenter();
        }
        if (mPresenter != null) {
            mPresenter.attachView(this);
        }

        App.getInstance().addActivity(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //禁止横屏
        if (findViewById(R.id.com_toolbar) != null) initComToolBar();

        initEventAndData(savedInstanceState);
    }

    protected abstract void initComToolBar();

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onResume(mContext);
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPause(mContext);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null)
            mPresenter.detachView();
//        mUnBinder.unbind();
        App.getInstance().removeActivity(this);
    }

    protected LoadingDialog loadingDialog;//加载进度框

    /**
     * 显示进度Dialog
     */
    protected void showLoading(boolean cancelable) {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this, cancelable);
        }
        loadingDialog.show();
    }

    /**
     * 取消loading
     */
    protected void dismissLaoding() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    protected abstract int getLayout();

    protected abstract void initEventAndData(@Nullable Bundle savedInstanceState);

    protected abstract T createPresenter();
}
